//
//  HJDBannerOneViewController.m
//  JYHospital
//
//  Created by 胡金东 on 16/5/16.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDBannerOneViewController.h"
#import "HJDBannerOneCell.h"
#import "HJDBannerOneModel.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "MJRefresh.h"


@interface HJDBannerOneViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    int pageS;
    int pages;
    int n;
   
}

@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * dataArray;
@property (nonatomic,strong)  NSString * pageCount;




@end

@implementation HJDBannerOneViewController

-(NSMutableArray *)dataArray
{
    if (_dataArray ==nil) {
        
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"坐诊专家";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor getColorWithHexNumber:@"848484"]}];

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
//    self.dataArray = [HJDBannerOneModel infoArray];
     self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(backBtnClick) image:@"︿" HighImage:nil];
    
   
    NSUserDefaults *phonede = [NSUserDefaults standardUserDefaults];
    NSString *phone = [phonede objectForKey:@"phonenum"];
    
    self.pageCount = @"1";
    NSString *url = @"/app/doctorList.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
   
    params[@"pageSize"]= self.pageCount;
    params[@"phone"]= phone;

    
    [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
         NSLog(@"res------%@",responseObject);
        NSDictionary *info =(NSDictionary *)responseObject;
        NSMutableArray *arrayR = info[@"resultMap"][@"result"];
        NSString *sum = info[@"resultMap"][@"count"];
        
        NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
        [defaS setObject:sum forKey:@"countSum"];
        
        
        
        self.dataArray = (NSMutableArray *)[HJDBannerOneModel mj_objectArrayWithKeyValuesArray:arrayR];
       
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"服务器升级，请稍后再试"];
//        NSLog(@"error----%@",error);
    }];
    
    
    //添加下拉刷新控件
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStatus)];
    //    添加上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadOldStatus)];
    
    
    NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
    NSString *page = [defa objectForKey:@"countSum"];
    pageS = [page intValue];
//    NSLog(@"pagesS%d",pageS);
    //   总页数
    pages = (pageS/10) +1 ;
//    NSLog(@"page%d",pages);
    n = 1;


}
//返回
-(void)backBtnClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)loadNewStatus{
    
//    
//    NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
//    NSString *page = [defaS objectForKey:@"countSum"];
//    pageS = [page intValue];
//    NSLog(@"pagesS%d",pageS);
//    
//    if (pageS%10 != 0) {
//        if (n <= 0) {
//            return;
//        }
//        n -= 1;
//        
//        NSLog(@"nnnn%d",n);
//        
//    }
    
    if (n < 1) {
        
        
        
        self.pageCount = [NSString stringWithFormat:@"%d",n];
        
               NSUserDefaults *phonede = [NSUserDefaults standardUserDefaults];
        NSString *phone = [phonede objectForKey:@"phonenum"];
        
        
        NSString *url = @"/app/doctorList.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];

//        [params setObject:phone forKey:@"phone"];
//        [params setObject:self.pageCount forKey:@"pageSize"];
        params[@"pageSize"]= self.pageCount;
        params[@"phone"]= phone;
      
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self.tableView.mj_header endRefreshing];
            
            NSDictionary *info =(NSDictionary *)responseObject;
            NSMutableArray *arrayR = info[@"resultMap"][@"record"];
            
            
            NSArray *statuses = (NSMutableArray *)[HJDBannerOneModel mj_objectArrayWithKeyValuesArray:arrayR];
            //防止覆盖后面的数据
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
            //刷新最新的数据，插入到最前面，防止覆盖后面的数据
            [self.dataArray insertObjects:statuses atIndexes:indexSet];
            
            
            [self.tableView reloadData];
            
            
            //        NSLog(@"res------%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"error----%@",error);
        }];
        
    }else{
//    [MBProgressHUD showSuccess:@"没有新数据了"];
        [self.tableView.mj_header endRefreshing];
        
    }
}

-(void)loadOldStatus
{
    NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
    NSString *page = [defaS objectForKey:@"countSum"];
    pageS = [page intValue];
//    NSLog(@"pagesS%d",pageS);
    
    if (pageS%10 != 0) {
        n += 1;
//        NSLog(@"nnnn%d",n);
        
    }else{
        n+= 1;
    }
    if (n <= pages) {
        
        
        self.pageCount = [NSString stringWithFormat:@"%d",n];
        
     
        NSUserDefaults *phonede = [NSUserDefaults standardUserDefaults];
        NSString *phone = [phonede objectForKey:@"phonenum"];
        
        
        NSString *url = @"/app/doctorList.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"pageSize"]= self.pageCount;
        params[@"phone"]= phone;
  
        
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [self.tableView.mj_footer endRefreshing];
            
            NSDictionary *info =(NSDictionary *)responseObject;
            NSMutableArray *arrayR = info[@"resultMap"][@"record"];
            NSArray *arr= (NSMutableArray *)[HJDBannerOneModel mj_objectArrayWithKeyValuesArray:arrayR];
            
            [self.dataArray addObjectsFromArray:arr];
            
            
            [self.tableView reloadData];
            
            
                    NSLog(@"res------%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error----%@",error);
        }];
    }else{
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:@"最后一页了"];
    }
    
}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    HJDBannerOneCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[HJDBannerOneCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    HJDBannerOneModel * model = self.dataArray[indexPath.row];
    NSLog(@"head==%@",model.headUrl);
    if (model.headUrl==nil) {
        cell.ImageV.image = [UIImage imageNamed:@"专家头像"];
    }else{

        NSString *urlStr =[NSString stringWithFormat:@"%@/%@",headImageUrl,model.headUrl];
        
        cell.ImageV.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]];
    }
   
    cell.name.text = model.name;
    cell.departments.text = @"妇科";
    cell.post.text = model.department;
    cell.introduce.text = model.major;
    cell.year.text = model.yeas;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}

@end
